import { prisma } from '../../../utils/prisma'
import { getUserIdOrThrow } from '../../../utils/guard'
import { z } from 'zod'

const bodySchema = z.object({
  title: z.string().min(1),
  costPoints: z.number().int().positive(),
  limitPerWeek: z.number().int().positive().optional()
})

export default eventHandler(async (event) => {
  const userId = getUserIdOrThrow(event)
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const { title, costPoints, limitPerWeek } = parsed.data
  const template = await prisma.rewardTemplate.create({
    data: { userId, title, costPoints, limitPerWeek }
  })
  return { template }
})


